<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>吸血鬼幸存者简易版</title>
    <style>
         body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #000;
        font-family: Arial, sans-serif;
    }
  #statsContainer {
    position: absolute;
    top: 10px;
    left: 10px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    z-index: 3;
}

.stat {
    color: #fff;
    font-size: 18px;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 8px 12px;
    border-radius: 6px;
    min-width: 160px;
}


.stat i {
    margin-right: 8px;
    color: #ffdd55;
}

.stat i {
    margin-right: 8px;
    color: #ffdd55;
}

    /* 背景图 */
    #gifBackground {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 120%;
        height: auto;
        z-index: -1; /* 保持最低层 */
        image-rendering: auto;
        filter: brightness(0.9);
    }

    /* Canvas 游戏主画布 */
    canvas {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1; /* 在背景之上，在 UI 之下 */
    }

    /* 所有 UI 元素 */
    .ui,
    .game-over,
    .upgrade-menu,
    .start-menu,
    .health-bar,
    .experience-bar,
    .fps-counter,
    .level-indicator {
        position: absolute;
        z-index: 2; /* 最上层，保证可见 */
    }
        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            color: white;
            display: none;
        }
        .upgrade-menu {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            color: white;
            display: none;
        }
        .upgrade-btn {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 5px;
        }
        .start-menu {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 40px;
            border-radius: 10px;
            text-align: center;
            color: white;
        }
        .start-btn {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 20px;
            margin: 20px 2px;
            cursor: pointer;
            border-radius: 5px;
        }
        .fps-counter {
            position: absolute;
            top: 10px;
            right: 10px;
            color: white;
            font-size: 14px;
            pointer-events: none;
        }
        
        /* 生命条样式 - 修改后 */
.health-bar {
    position: absolute;
    top: 20px; /* 距离顶部稍大一些 */
    left: 50%;
    transform: translateX(-50%); /* 水平居中 */
    width: 300px; /* 原来是 200px，现在加宽 */
    height: 20px; /* 原来是 15px，变高一点 */
    background-color: #660000;
    border-radius: 10px; /* 更圆润 */
    z-index: 100;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); /* 可选：增加阴影效果 */
}

/* 血量填充部分 */
.health-fill {
    height: 100%;
    background-color: #ff0000;
    border-radius: 10px;
    transition: width 0.3s ease;
}
        /* 经验条样式 */
        .experience-bar {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            width: 300px;
            height: 12px;
            background-color: #444;
            border-radius: 6px;
            z-index: 100;
        }
        .experience-fill {
            height: 100%;
            background-color: #00ff00;
            border-radius: 4px;
            transition: width 0.3s ease;
        }
        
        /* 玩家头顶等级样式 */
        .level-indicator {
            position: absolute;
            font-size: 24px;
            color: #00ff00;
            font-weight: bold;
            text-shadow: 0 0 5px #000;
        }
        .dice-result {
    color: #ffcc00;
    font-weight: bold;
    text-shadow: 0 0 3px #000;
}
    </style>
</head>
<body>
    <img id="gifBackground" src="3.png"
     style="position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 120%;
            height: auto;
            z-index: -1;
            image-rendering: auto;
            filter: brightness(0.9);" />
<!-- 引入 Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<!-- 属性信息容器 -->
<div id="statsContainer">
    <div class="stat"><i class="fas fa-star"></i> 分数: <span id="score">0</span></div>
    <div class="stat"><i class="fas fa-level-up-alt"></i> 等级: <span id="level">1</span></div>
    <div class="stat"><i class="fas fa-clock"></i> 时间: <span id="time">0</span></div>
    <div class="stat"><i class="fas fa-sword"></i> 攻击力: <span id="damage">10</span></div>

</div>
    <div class="fps-counter" id="fpsCounter">FPS: 0</div>
    <div class="game-over" id="gameOver">
        <h2>游戏结束</h2>
        <p>最终分数: <span id="finalScore">0</span></p>
        <button onclick="restartGame()">重新开始</button>
    </div>
    <div class="upgrade-menu" id="upgradeMenu">
        <h2>升级! 🎲</h2>
<p style="color:#ffdd55;">你有 50% 概率掷一次骰子，点数越高奖励越丰富！</p>
        <div id="upgrades"></div>
        <div class="dice-result" id="diceResult" style="margin-top: 10px; font-size: 18px; display: none;"></div>
    </div>
    
    <div class="start-menu" id="startMenu">
        <h1>吸血鬼幸存者简易版</h1>
        <p>WASD移动，鼠标控制攻击方向</p>
        <p style="color:#00ffff;">按下空格键使用环形冲击波！</p>
         <p style="color:#00ffff;">(要解锁)</p>
        <button class="start-btn" onclick="startGame()">开始游戏</button>
    </div>
    
    <!-- 生命条 -->
    <div class="health-bar">
        <div class="health-fill" id="healthFill"></div>
    </div>
  
    <!-- 经验条 -->
    <div class="experience-bar">
        <div class="experience-fill" id="experienceFill"></div>
    </div>
    
    <canvas id="gameCanvas"></canvas>

    <script>
        // 获取Canvas和上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 设置Canvas尺寸
        function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        }
        
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
        
        // 游戏状态
        const gameState = {
            player: {
                x: canvas.width / 2,
                y: canvas.height / 2,
                radius: 15,
                speed: 5,
                health: 100,
                maxHealth: 100,
                damage: 10,
                attackSpeed: 100, // 攻击间隔(ms)
                lastAttack: 0,
                level: 1,
                experience: 0,
                experienceToLevel: 100,
                weapon: 'basic',
                shotgunLevel: 0, // 新增霰弹枪等级
                 bulletSizeMultiplier: 1.0,
            },
            projectiles: [],
            enemies: [],
            explosions: [],
            particles: [], // 新增：粒子系统
            keys: {
                w: false,
                a: false,
                s: false,
                d: false
            },
            mouse: {
                x: 0,
                y: 0
            },
            gameTime: 0,
            score: 0,
            lastEnemySpawn: 0,
            enemySpawnRate: 1000, // 敌人生成间隔(ms)
            isGameOver: false,
            isUpgrading: false,
            levelUpThreshold: 100, // 升级所需经验
            powerUps: [
                { id: 'health', name: '增加生命值', effect: () => { 
                    gameState.player.maxHealth += 20; 
                    gameState.player.health = gameState.player.maxHealth; 
                    updateHealthBar(); // 新增：升级时更新生命条
                } 
            },
                {
    id: 'radialWave',
    name: '解锁环形冲击波',
    effect: () => {
        gameState.player.hasRadialWave = true;
        gameState.player.radialWaveCooldown = 100; // 冷却时间：10秒
        gameState.player.lastRadialWaveTime = 0;
    }
},
                { id: 'speed', name: '增加移动速度', effect: () => { gameState.player.speed += 0.5; } },
                { id: 'damage', name: '增加攻击力', effect: () => { gameState.player.damage += 2; } },
                { id: 'attackSpeed', name: '增加攻击速度', effect: () => { gameState.player.attackSpeed = Math.max(50, gameState.player.attackSpeed - 10); } },
                {
    id: 'bulletSize',
    name: '增强子弹尺寸',
    effect: () => {
        gameState.player.bulletSizeMultiplier += 0.3; // 每次升级增加30%
        if (gameState.player.bulletSizeMultiplier > 2.0) {
            gameState.player.bulletSizeMultiplier = 2.0; // 最多两倍
        }
        console.log("【升级】子弹尺寸提升至 x" + gameState.player.bulletSizeMultiplier.toFixed(1));
    }
},
                {
    id: 'shotgun',
    name: '强化霰弹枪',
    effect: () => {
        gameState.player.shotgunLevel += 1;
        if (gameState.player.shotgunLevel > 3) {
            gameState.player.shotgunLevel = 3; // 最大等级限制为3
        }
        gameState.player.weapon = 'shotgun';
    }
    
}
            ],
            accumulator: 0,
            lastFpsUpdate: 0,
            frameCount: 0,
            fps: 0,
            experienceBar: {
                width: 0,
                maxWidth: 300
            },
            levelIndicator: {
                x: 0,
                y: 0,
                alpha: 0,
                timer: 0
            },
            enemySpawnRate: 1000,      // 初始敌人生成间隔（毫秒）
    lastEnemySpawn: 0,
    maxEnemies: 50,            // 最大敌人数量
    difficultyIncreaseInterval: 15000, // 每10秒提升一次难度
    lastDifficultyIncreaseTime: 0,
    enemySpeedMultiplier: 1.0,
        };
        
        // 初始化游戏
        function initGame() {
            // 重置游戏状态
            gameState.player.x = canvas.width / 2;
            gameState.player.y = canvas.height / 2;
            gameState.player.health = gameState.player.maxHealth;
            gameState.player.level = 1;
            gameState.player.experience = 0;
            gameState.player.experienceToLevel = 100;
            gameState.player.weapon = 'basic';
            gameState.projectiles = [];
            gameState.enemies = [];
            gameState.explosions = [];
            gameState.particles = []; // 清空粒子
            gameState.gameTime = 0;
            gameState.score = 0;
            gameState.lastEnemySpawn = 0;
            gameState.enemySpawnRate = 1000;
            gameState.isGameOver = false;
            gameState.isUpgrading = false;
            gameState.accumulator = 0;
            
            // 更新UI（移除了生命值文本）
            document.getElementById('score').textContent = gameState.score;
            document.getElementById('level').textContent = gameState.player.level;
            document.getElementById('time').textContent = Math.floor(gameState.gameTime);
            
            // 初始化生命条和经验条
            updateHealthBar();
            updateExperienceBar();
            
            // 隐藏菜单
            document.getElementById('startMenu').style.display = 'none';
            document.getElementById('gameOver').style.display = 'none';
            document.getElementById('upgradeMenu').style.display = 'none';
            
            // 开始游戏循环
            let lastTime = 0;
            gameState.lastFpsUpdate = performance.now();
            gameState.frameCount = 0;
            
            function gameLoop(timestamp) {
                if (gameState.isGameOver) return;
                
                // 计算FPS
                gameState.frameCount++;
                const now = performance.now();
                if (now - gameState.lastFpsUpdate >= 1000) {
                    gameState.fps = Math.round((gameState.frameCount * 1000) / (now - gameState.lastFpsUpdate));
                    document.getElementById('fpsCounter').textContent = `FPS: ${gameState.fps}`;
                    gameState.frameCount = 0;
                    gameState.lastFpsUpdate = now;
                }
                
                // 计算时间增量
                let deltaTime = timestamp - lastTime;
                lastTime = timestamp;
                
                // 防止长帧导致的物理异常
                if (deltaTime > 1000) deltaTime = 16; // 约60FPS
                
                if (!gameState.isUpgrading) {
                    // 累积时间，使用固定时间步长更新游戏状态
                    gameState.accumulator += deltaTime;
                    
                    while (gameState.accumulator >= 16) { // 约60FPS
                        // 更新游戏时间
                        gameState.gameTime += 16 / 1000;
                        document.getElementById('time').textContent = Math.floor(gameState.gameTime);
                        
                        // 移动玩家
                        movePlayer();
                        
                        // 玩家攻击
                        playerAttack(timestamp);
                        
                        // 生成敌人
                        spawnEnemy(timestamp);
                        
                        // 移动敌人
                        moveEnemies();
                        
                        // 移动子弹
                        moveProjectiles();
                        
                        // 更新爆炸效果
                        updateExplosions();
                        
                        // 更新粒子系统
                        updateParticles(16);
                        checkRadialWaveDamage();
                        gameState.accumulator -= 16;
                    }
                }
                
                // 绘制游戏
                drawGame();
                
                // 继续游戏循环
                requestAnimationFrame(gameLoop);
            }
            
            requestAnimationFrame(gameLoop);
        }
        
        // 开始游戏
        function startGame() {
            initGame();
        }
        
        // 重新开始游戏
        function restartGame() {
            initGame();
        }
        
        // 处理键盘事件
        window.addEventListener('keydown', (e) => {
            if (e.key === 'w') gameState.keys.w = true;
            if (e.key === 'a') gameState.keys.a = true;
            if (e.key === 's') gameState.keys.s = true;
            if (e.key === 'd') gameState.keys.d = true;
        });
        
        window.addEventListener('keyup', (e) => {
            if (e.key === 'w') gameState.keys.w = false;
            if (e.key === 'a') gameState.keys.a = false;
            if (e.key === 's') gameState.keys.s = false;
            if (e.key === 'd') gameState.keys.d = false;
        });
        
        // 处理鼠标移动事件
        canvas.addEventListener('mousemove', (e) => {
            const rect = canvas.getBoundingClientRect();
            gameState.mouse.x = e.clientX - rect.left;
            gameState.mouse.y = e.clientY - rect.top;
        });
// 空格键触发环形冲击波
window.addEventListener('keydown', (e) => {
    if (e.code === 'Space' && gameState.player.hasRadialWave && !gameState.isUpgrading) {
        useRadialWave();
    }
});
        // 移动玩家
        function movePlayer() {
            let dx = 0;
            let dy = 0;
            
            if (gameState.keys.w) dy -= gameState.player.speed;
            if (gameState.keys.s) dy += gameState.player.speed;
            if (gameState.keys.a) dx -= gameState.player.speed;
            if (gameState.keys.d) dx += gameState.player.speed;
            
            // 归一化移动向量，防止对角线移动过快
            if (dx !== 0 || dy !== 0) {
                const length = Math.sqrt(dx * dx + dy * dy);
                dx /= length;
                dy /= length;
                
                dx *= gameState.player.speed;
                dy *= gameState.player.speed;
                
                // 边界检查
                if (gameState.player.x + dx > gameState.player.radius && 
                    gameState.player.x + dx < canvas.width - gameState.player.radius) {
                    gameState.player.x += dx;
                }
                
                if (gameState.player.y + dy > gameState.player.radius && 
                    gameState.player.y + dy < canvas.height - gameState.player.radius) {
                    gameState.player.y += dy;
                }
            }
        
            // 更新等级显示位置
            gameState.levelIndicator.x = gameState.player.x;
            gameState.levelIndicator.y = gameState.player.y - gameState.player.radius - 20;
        }
        
        // 玩家攻击
        function playerAttack(timestamp) {
            if (timestamp - gameState.player.lastAttack < gameState.player.attackSpeed) {
                return;
            }

            gameState.player.lastAttack = timestamp;

            const dx = gameState.mouse.x - gameState.player.x;
            const dy = gameState.mouse.y - gameState.player.y;
            const angle = Math.atan2(dy, dx);

            if (gameState.player.weapon === 'basic') {
                // 基础子弹
                gameState.projectiles.push({
                    x: gameState.player.x,
                    y: gameState.player.y,
                    radius: 5 * gameState.player.bulletSizeMultiplier, // 使用缩放因子
                    speed: 8,
                    damage: gameState.player.damage,
                    angle,
                    color: '#ffcc00'
                });
            } else if (gameState.player.weapon === 'shotgun') {
                let bulletCount = 3; // 默认3发
                if (gameState.player.shotgunLevel >= 2) bulletCount = 5;
                if (gameState.player.shotgunLevel >= 3) bulletCount = 7;

                for (let i = -(Math.floor(bulletCount / 2)); i <= Math.floor(bulletCount / 2); i++) {
                    const spreadAngle = angle + i * 0.1;
                    gameState.projectiles.push({
                        x: gameState.player.x,
                        y: gameState.player.y,
                        radius: 4 * gameState.player.bulletSizeMultiplier, // 使用缩放因子
                        speed: 7,
                        damage: gameState.player.damage * 0.7,
                        angle: spreadAngle,
                        color: '#ff6600'
                    });
                }
            }

            if (gameState.projectiles.length > 100) {
                gameState.projectiles.shift();
            }
            
            // 添加攻击粒子效果
            const particleCount = 3; // 每次攻击生成3个粒子
            for (let i = 0; i < particleCount; i++) {
                const angle = Math.random() * Math.PI * 2; // 随机角度
                const speed = 2 + Math.random() * 3; // 随机速度
                const lifespan = 800 + Math.random() * 400; // 粒子存活时间（毫秒）
                
                gameState.particles.push({
                    x: gameState.player.x,
                    y: gameState.player.y,
                    angle,
                    speed,
                    lifespan,
                    startLifespan: lifespan, // 存储初始寿命用于计算
                    startSize: 3,
                    endSize: 1,
                    color: '#ffdd55', // 金黄色粒子
                    alpha: 1
                });
            }
        }
        function checkRadialWaveDamage() {
    // 只有解锁了环形波才生效
    if (!gameState.player.hasRadialWave) return;

    const waveRadius = 150; // 和之前一致
    const damagePerSecond = gameState.player.damage * 2;
    
    // 每帧造成一定伤害（根据FPS）
    const damagePerFrame = damagePerSecond / gameState.fps;

    gameState.enemies.forEach((enemy, index) => {
        const dx = enemy.x - gameState.player.x;
        const dy = enemy.y - gameState.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance <= waveRadius) {
            enemy.health -= damagePerFrame;

            // 添加击中粒子效果
            addHitParticles(enemy.x, enemy.y, enemy.color);

            // 检查是否死亡
            if (enemy.health <= 0) {
                gameState.score += enemy.score;
                gameState.player.experience += enemy.experience;
                gameState.enemies.splice(index, 1);
                updateExperienceBar();
            }
        }
    });
}
        function useRadialWave() {
    const now = performance.now();
    if (now - gameState.player.lastRadialWaveTime < gameState.player.radialWaveCooldown) {
        return; // 冷却中
    }
 console.log("【技能】尝试使用环形冲击波");
    
    gameState.player.lastRadialWaveTime = now;

    // 创建粒子效果（环形扩散）
    const waveCount = 8; // 粒子数量
    for (let i = 0; i < waveCount; i++) {
        const angle = (Math.PI * 2 / waveCount) * i;
        gameState.particles.push({
            x: gameState.player.x,
            y: gameState.player.y,
            radius: 5,
            maxRadius: 200,
            alpha: 1,
            color: '#00ffff',
            lifespan: 500,
            startLifespan: 500,
            type: 'radialWave',
            angle
        });
    }

    // 对范围内敌人造成伤害
    const waveRadius = 100;
    let enemiesHit = 0;

    gameState.enemies.forEach((enemy, index) => {
        const dx = enemy.x - gameState.player.x;
        const dy = enemy.y - gameState.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance <= waveRadius) {
            const damage = gameState.player.damage * 2;
            enemy.health -= damage;

            addHitParticles(enemy.x, enemy.y, enemy.color);

            if (enemy.health <= 0) {
                enemiesHit++;
                gameState.score += enemy.score;
                gameState.player.experience += enemy.experience;
                gameState.enemies.splice(index, 1);
                updateExperienceBar();
            }
        }
    });

    document.getElementById('score').textContent = gameState.score;
    document.getElementById('damage').textContent = Math.floor(gameState.player.damage);
}
        function spawnEnemy(timestamp) {
            // 控制最大敌人数量
            if (gameState.enemies.length >= gameState.maxEnemies) return;

            // 控制敌人生成频率
            if (timestamp - gameState.lastEnemySpawn < gameState.enemySpawnRate) return;

            // 动态调整难度
            if (timestamp - gameState.lastDifficultyIncreaseTime > gameState.difficultyIncreaseInterval) {
                gameState.lastDifficultyIncreaseTime = timestamp;

                // 敌人生成更快（每15秒减小30ms，最低300ms）
                gameState.enemySpawnRate = Math.max(300, gameState.enemySpawnRate - 30);

                // 敌人更强（速度提升变慢）
                gameState.enemySpeedMultiplier += 0.05; // 原为 0.1

                console.log(`【难度提升】下个敌人将在 ${gameState.enemySpawnRate}ms 后生成`);
            }
            gameState.lastEnemySpawn = timestamp;

            // 随机生成敌人位置（屏幕边缘）
            let x, y;
            if (Math.random() < 0.5) {
                x = Math.random() < 0.5 ? -50 : canvas.width + 50;
                y = Math.random() * canvas.height;
            } else {
                x = Math.random() * canvas.width;
                y = Math.random() < 0.5 ? -50 : canvas.height + 50;
            }

            // 随机敌人类型
            const difficultyFactor = 1 + gameState.gameTime / 60; // 时间越长，敌人越强
            let enemyType;
            const randomNum = Math.random();

            if (randomNum < 0.4) {
                // 普通敌人
                enemyType = {
                    radius: 15 + Math.random() * 10,
                    speed: (1 + Math.random() * 1.5) * gameState.enemySpeedMultiplier * difficultyFactor,
                    health: 20 + Math.random() * 30 * difficultyFactor,
                    damage: 5 * difficultyFactor,
                    color: '#ff0000',
                    score: 10, // 击杀分数
                    experience: 10 // 击杀获得经验
                };
            } else if (randomNum < 0.7) {
                // 快速敌人
                enemyType = {
                    radius: 10 + Math.random() * 5,
                    speed: (3 + Math.random() * 2) * gameState.enemySpeedMultiplier * difficultyFactor,
                    health: 10 + Math.random() * 20 * difficultyFactor,
                    damage: 3 * difficultyFactor,
                    color: '#00ff00',
                    score: 15,
                    experience: 15
                };
            } else if (randomNum < 0.9) {
                // 大型敌人
                enemyType = {
                    radius: 25 + Math.random() * 15,
                    speed: (0.5 + Math.random() * 0.5) * gameState.enemySpeedMultiplier * difficultyFactor,
                    health: 50 + Math.random() * 50 * difficultyFactor,
                    damage: 10 * difficultyFactor,
                    color: '#0000ff',
                    score: 25,
                    experience: 25
                };
            } else {
                // 精英敌人
                enemyType = {
                    radius: 30 + Math.random() * 20,
                    speed: (2 + Math.random() * 1) * gameState.enemySpeedMultiplier * difficultyFactor,
                    health: 100 + Math.random() * 100 * difficultyFactor,
                    damage: 15 * difficultyFactor,
                    color: '#ff00ff',
                    score: 50,
                    experience: 50
                };
            }

            gameState.enemies.push({
                x,
                y,
                ...enemyType
            });
        }
        
        // 移动敌人
        function moveEnemies() {
            for (let i = gameState.enemies.length - 1; i >= 0; i--) {
                const enemy = gameState.enemies[i];
                
                // 计算敌人到玩家的方向
                const dx = gameState.player.x - enemy.x;
                const dy = gameState.player.y - enemy.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 0) {
                    // 移动敌人
                    enemy.x += (dx / distance) * enemy.speed;
                    enemy.y += (dy / distance) * enemy.speed;
                    
                    // 检查碰撞
                    if (distance < enemy.radius + gameState.player.radius) {
                        // 敌人碰到玩家，造成伤害
                        gameState.player.health -= enemy.damage;
                        updateHealthBar(); // 更新生命条
                        
                        // 创建爆炸效果
                        gameState.explosions.push({
                            x: enemy.x,
                            y: enemy.y,
                            radius: enemy.radius * 1.5,
                            alpha: 1,
                            color: '#ff0000'
                        });
                        
                        // 移除敌人
                        gameState.enemies.splice(i, 1);
                        
                        // 增加分数
                        gameState.score += enemy.score;
                        document.getElementById('score').textContent = gameState.score;
                        
                        // 检查游戏是否结束
                        if (gameState.player.health <= 0) {
                            gameOver();
                        }
                        
                        break;
                    }
                }
            }
        }
        
        // 移动子弹
        function moveProjectiles() {
            for (let i = gameState.projectiles.length - 1; i >= 0; i--) {
                const projectile = gameState.projectiles[i];
                
                // 移动子弹
                projectile.x += Math.cos(projectile.angle) * projectile.speed;
                projectile.y += Math.sin(projectile.angle) * projectile.speed;
                
                // 检查子弹是否超出屏幕
                if (projectile.x < -100 || projectile.x > canvas.width + 100 || 
                    projectile.y < -100 || projectile.y > canvas.height + 100) {
                    gameState.projectiles.splice(i, 1);
                    continue;
                }
                
                // 检查子弹与敌人的碰撞
                for (let j = gameState.enemies.length - 1; j >= 0; j--) {
                    const enemy = gameState.enemies[j];
                    const dx = projectile.x - enemy.x;
                    const dy = projectile.y - enemy.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance < projectile.radius + enemy.radius) {
                        // 敌人受伤
                        enemy.health -= projectile.damage;
                        
                        // 移除子弹
                        gameState.projectiles.splice(i, 1);
                        
                        // 添加击中粒子效果
                        addHitParticles(projectile.x, projectile.y, enemy.color);
                        
                        // 检查敌人是否死亡
                        if (enemy.health <= 0) {
                            // 创建爆炸效果
                            gameState.explosions.push({
                                x: enemy.x,
                                y: enemy.y,
                                radius: enemy.radius * 1.5,
                                alpha: 1,
                                color: enemy.color
                            });
                            
                            // 添加死亡粒子效果
                            const deathParticleCount = 15; // 每个敌人死亡生成15个粒子
                            for (let k = 0; k < deathParticleCount; k++) {
                                const angle = Math.random() * Math.PI * 2;
                                const speed = 1.5 + Math.random() * 4;
                                const lifespan = 600 + Math.random() * 300;
                                
                                gameState.particles.push({
                                    x: enemy.x,
                                    y: enemy.y,
                                    angle,
                                    speed,
                                    lifespan,
                                    startLifespan: lifespan,
                                    startSize: enemy.radius * 0.5,
                                    endSize: 0,
                                    color: enemy.color, // 使用敌人颜色
                                    alpha: 1
                                });
                            }
                            
                            // 移除敌人
                            gameState.enemies.splice(j, 1);
                            
                            // 增加分数和经验
                            gameState.score += enemy.score;
                            gameState.player.experience += enemy.experience;
                            
                            // 更新UI
                            document.getElementById('score').textContent = gameState.score;
                            updateExperienceBar();
                            
                            // 检查是否升级
                            if (gameState.player.experience >= gameState.player.experienceToLevel) {
                                levelUp();
                            }
                        }
                        
                        break;
                    }
                }
            }
        }
        
        // 添加击中粒子效果
        function addHitParticles(x, y, enemyColor) {
            const particleCount = 8; // 击中效果粒子数量
            const particleSpeed = 2; // 粒子速度基数
            
            for (let i = 0; i < particleCount; i++) {
                // 围绕击中位置随机角度发射粒子
                const angle = Math.random() * Math.PI * 2;
                const speed = particleSpeed * (0.5 + Math.random() * 0.5);
                const lifespan = 400 + Math.random() * 200; // 粒子存活时间
                
                // 粒子颜色：使用敌人颜色，但稍微调整以增加变化
                let particleColor;
                if (enemyColor === '#ff0000') {
                    // 红色敌人 -> 橙色/黄色粒子
                    particleColor = Math.random() > 0.5 ? '#ffaa00' : '#ffff00';
                } else if (enemyColor === '#00ff00') {
                    // 绿色敌人 -> 浅绿色/青色粒子
                    particleColor = Math.random() > 0.5 ? '#00ffaa' : '#00ffff';
                } else if (enemyColor === '#0000ff') {
                    // 蓝色敌人 -> 紫色/深蓝色粒子
                    particleColor = Math.random() > 0.5 ? '#aa00ff' : '#0000aa';
                } else if (enemyColor === '#ff00ff') {
                    // 紫色敌人 -> 粉色/亮紫色粒子
                    particleColor = Math.random() > 0.5 ? '#ffaaee' : '#ee00ff';
                } else {
                    // 默认使用金黄色
                    particleColor = '#ffdd55';
                }
                
                gameState.particles.push({
                    x,
                    y,
                    angle,
                    speed,
                    lifespan,
                    startLifespan: lifespan,
                    startSize: 2 + Math.random(), // 随机大小
                    endSize: 0,
                    color: particleColor,
                    alpha: 1
                });
            }
        }
        
        // 升级
        function levelUp() {
            // 增加等级
            gameState.player.level++;

            // 计算下一级所需经验
            gameState.player.experienceToLevel = Math.floor(gameState.player.experienceToLevel * 1.5);

            // 重置当前经验
            gameState.player.experience = 0;
            updateExperienceBar();

            // 显示头顶等级
            gameState.levelIndicator.alpha = 1;
            gameState.levelIndicator.timer = 60; // 显示1秒（60帧）

            // 更新UI
            document.getElementById('level').textContent = gameState.player.level;

            // 显示升级菜单
            showUpgradeMenu();
        }
        
        function rollDice() {
            return Math.floor(Math.random() * 6) + 1;
        }

        // 根据点数应用不同奖励
        function applyDiceReward(diceValue) {
            const resultDiv = document.getElementById('diceResult');
            let rewardText = '';

            switch (diceValue) {
                case 1:
                    rewardText = '运气不佳，没有额外奖励。';
                    break;
                case 2:
                case 3:
                    gameState.player.health = Math.min(gameState.player.maxHealth, gameState.player.health + 10);
                    updateHealthBar();
                    rewardText = '恢复了 10 点生命值！';
                    break;
                case 4:
                case 5:
                    gameState.player.damage += 2;
                    rewardText = '攻击力提升了 2 点！';
                    break;
                case 6:
                    gameState.player.speed += 1;
                    gameState.player.attackSpeed = Math.max(50, gameState.player.attackSpeed - 15);
                    rewardText = '移动速度和攻击速度都得到了提升！';
                    break;
            }
console.log("所有可选升级项：", gameState.powerUps.map(u => u.name));
            resultDiv.textContent = `🎲 掷得了 ${diceValue} 点：${rewardText}`;
            resultDiv.style.display = 'block';
        }

        // 显示升级菜单
        function showUpgradeMenu() {
            gameState.isUpgrading = true;
            let diceAvailable = false; // 是否有骰子选项
            let diceRolled = false;    // 是否已掷骰子

            requestAnimationFrame(() => {
                const upgradesContainer = document.getElementById('upgrades');
                upgradesContainer.innerHTML = '';
                const resultDiv = document.getElementById('diceResult');
                resultDiv.style.display = 'none';

               // 过滤掉已解锁的技能（例如：radialWave）
const availableUpgrades = gameState.powerUps.filter(upgrade => {
    // 如果是 "radialWave"，且玩家已经拥有，则不显示
    if (upgrade.id === 'radialWave' && gameState.player.hasRadialWave) {
        return false;
    }
    // 其他技能默认都可用
    return true;
});

// 随机排序并选择前三个
const shuffledUpgrades = [...availableUpgrades].sort(() => 0.5 - Math.random());
const selectedUpgrades = shuffledUpgrades.slice(0, 3);

                // 创建按钮前先判断是否有骰子选项
                if (Math.random() < 0.5) {
                    diceAvailable = true;

                    const diceButton = document.createElement('button');
                    diceButton.className = 'upgrade-btn';
                    diceButton.textContent = '🎲 掷得额外奖励';
                    diceButton.style.marginTop = '20px';
                    diceButton.disabled = false;

                    diceButton.onclick = () => {
                        const diceValue = rollDice();
                        applyDiceReward(diceValue);
                        diceRolled = true;
                        diceButton.disabled = true;
                        diceButton.textContent = '已获得奖励';

                        // 掷得奖励后允许选择技能
                        upgradeButtons.forEach(btn => btn.disabled = false);
                    };

                    upgradesContainer.appendChild(diceButton);
                }

                // 创建升级按钮（初始禁用）
                const upgradeButtons = [];

                selectedUpgrades.forEach(upgrade => {
                    const btn = document.createElement('button');
                    btn.className = 'upgrade-btn';
                    btn.textContent = upgrade.name;
                    btn.disabled = diceAvailable && !diceRolled; // 如果有骰子且未掷，则禁用

                    btn.onclick = () => {
                        upgrade.effect();

                        // 更新UI
                        document.getElementById('healthFill').style.width = `${(gameState.player.health / gameState.player.maxHealth) * 100}%`;
                        document.getElementById('damage').textContent = Math.floor(gameState.player.damage);

                        // 关闭菜单并继续游戏
                        document.getElementById('upgradeMenu').style.display = 'none';
                        gameState.isUpgrading = false;

                        cleanupObjects();
                    };

                    upgradesContainer.appendChild(btn);
                    upgradeButtons.push(btn);
                });

                // 添加提示文字（可选）
                const hint = document.createElement('p');
                hint.style.color = '#ffdd55';
                hint.style.marginTop = '10px';
                hint.textContent = '请先完成骰子奖励再选择技能';
                if (diceAvailable) {
                    upgradesContainer.appendChild(hint);
                }

                document.getElementById('upgradeMenu').style.display = 'block';
            });
        }
        
        // 对象清理，优化内存使用
        function cleanupObjects() {
            // 移除超出屏幕的子弹
            gameState.projectiles = gameState.projectiles.filter(projectile => {
                return projectile.x > -100 && projectile.x < canvas.width + 100 && 
                       projectile.y > -100 && projectile.y < canvas.height + 100;
            });
            
            // 清理完全透明的爆炸效果
            gameState.explosions = gameState.explosions.filter(explosion => {
                return explosion.alpha > 0;
            });
            
            // 清理消失的粒子
            gameState.particles = gameState.particles.filter(particle => {
                return particle.alpha > 0;
            });
        }
        
        // 游戏结束
        function gameOver() {
            gameState.isGameOver = true;
            document.getElementById('finalScore').textContent = gameState.score;
            document.getElementById('gameOver').style.display = 'block';
        }
        
        // 更新爆炸效果
        function updateExplosions() {
            for (let i = gameState.explosions.length - 1; i >= 0; i--) {
                const explosion = gameState.explosions[i];
                
                // 爆炸扩大
                explosion.radius += 2;
                
                // 透明度降低
                explosion.alpha -= 0.05;
                
                // 如果透明度为0，移除爆炸
                if (explosion.alpha <= 0) {
                    gameState.explosions.splice(i, 1);
                }
            }
        }
        
       function updateParticles(deltaTime) {
    gameState.particles = gameState.particles.filter(particle => {
        if (particle.type === 'radialWave') {
            particle.lifespan -= deltaTime;
            particle.alpha = Math.max(0, particle.lifespan / particle.startLifespan);
            return particle.lifespan > 0;
        }

        // 更新普通粒子的位置
        particle.x += Math.cos(particle.angle) * particle.speed * (deltaTime / 16);
        particle.y += Math.sin(particle.angle) * particle.speed * (deltaTime / 16);

        // 更新生命周期
        particle.lifespan -= deltaTime;
        particle.alpha = Math.max(0, particle.lifespan / particle.startLifespan);

        // 计算大小
        const lifeRatio = particle.lifespan / particle.startLifespan;
        particle.size = particle.startSize * lifeRatio + particle.endSize * (1 - lifeRatio);

        return particle.lifespan > 0;
    });
}
        
        // 更新生命条函数
        function updateHealthBar() {
            const healthPercentage = Math.max(0, Math.min(1, gameState.player.health / gameState.player.maxHealth));
            document.getElementById('healthFill').style.width = `${healthPercentage * 100}%`;
        }
        
        // 更新经验条
        function updateExperienceBar() {
            const progress = Math.min(1, gameState.player.experience / gameState.player.experienceToLevel);
            gameState.experienceBar.width = gameState.experienceBar.maxWidth * progress;
            document.getElementById('experienceFill').style.width = `${progress * 100}%`;
        }
        
        // 辅助函数：十六进制颜色转RGB
        function hexToRgb(hex) {
            const r = parseInt(hex.slice(1, 3), 16);
            const g = parseInt(hex.slice(3, 5), 16);
            const b = parseInt(hex.slice(5, 7), 16);
            return `${r}, ${g}, ${b}`;
        }
        
        // 绘制游戏
        function drawGame() {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制玩家
            ctx.beginPath();
            ctx.arc(gameState.player.x, gameState.player.y, gameState.player.radius, 0, Math.PI * 2);
            ctx.fillStyle = '#0099ff';
            ctx.fill();
            
            // 绘制玩家眼睛（朝向鼠标）
            const eyeDistance = gameState.player.radius * 0.6;
            const eyeSize = gameState.player.radius * 0.2;
            const angle = Math.atan2(
                gameState.mouse.y - gameState.player.y, 
                gameState.mouse.x - gameState.player.x
            );
            
            ctx.beginPath();
            ctx.arc(
                gameState.player.x + Math.cos(angle) * eyeDistance, 
                gameState.player.y + Math.sin(angle) * eyeDistance, 
                eyeSize, 0, Math.PI * 2
            );
            ctx.arc(
                gameState.player.x + Math.cos(angle + Math.PI * 0.8) * eyeDistance, 
                gameState.player.y + Math.sin(angle + Math.PI * 0.8) * eyeDistance, 
                eyeSize, 0, Math.PI * 2
            );
            ctx.fillStyle = '#ffffff';
            ctx.fill();
            
            // 绘制瞳孔
            ctx.beginPath();
            ctx.arc(
                gameState.player.x + Math.cos(angle) * eyeDistance * 1.2, 
                gameState.player.y + Math.sin(angle) * eyeDistance * 1.2, 
                eyeSize * 0.5, 0, Math.PI * 2
            );
            ctx.arc(
                gameState.player.x + Math.cos(angle + Math.PI * 0.8) * eyeDistance * 1.2, 
                gameState.player.y + Math.sin(angle + Math.PI * 0.8) * eyeDistance * 1.2, 
                eyeSize * 0.5, 0, Math.PI * 2
            );
            ctx.fillStyle = '#000000';
            ctx.fill();
            
            // 绘制子弹
            gameState.projectiles.forEach(projectile => {
                ctx.beginPath();
                ctx.arc(projectile.x, projectile.y, projectile.radius, 0, Math.PI * 2);
                ctx.fillStyle = projectile.color;
                ctx.fill();
            });
            
            // 绘制敌人
            gameState.enemies.forEach(enemy => {
                ctx.beginPath();
                ctx.arc(enemy.x, enemy.y, enemy.radius, 0, Math.PI * 2);
                ctx.fillStyle = enemy.color;
                ctx.fill();
                
                // 绘制敌人眼睛（朝向玩家）
                const eyeDistance = enemy.radius * 0.6;
                const eyeSize = enemy.radius * 0.2;
                const angle = Math.atan2(
                    gameState.player.y - enemy.y, 
                    gameState.player.x - enemy.x
                );
                
                ctx.beginPath();
                ctx.arc(
                    enemy.x + Math.cos(angle) * eyeDistance, 
                    enemy.y + Math.sin(angle) * eyeDistance, 
                    eyeSize, 0, Math.PI * 2
                );
                ctx.arc(
                    enemy.x + Math.cos(angle + Math.PI * 0.8) * eyeDistance, 
                    enemy.y + Math.sin(angle + Math.PI * 0.8) * eyeDistance, 
                    eyeSize, 0, Math.PI * 2
                );
                ctx.fillStyle = '#ffffff';
                ctx.fill();
                
                // 绘制瞳孔
                ctx.beginPath();
                ctx.arc(
                    enemy.x + Math.cos(angle) * eyeDistance * 1.2, 
                    enemy.y + Math.sin(angle) * eyeDistance * 1.2, 
                    eyeSize * 0.5, 0, Math.PI * 2
                );
                ctx.arc(
                    enemy.x + Math.cos(angle + Math.PI * 0.8) * eyeDistance * 1.2, 
                    enemy.y + Math.sin(angle + Math.PI * 0.8) * eyeDistance * 1.2, 
                    eyeSize * 0.5, 0, Math.PI * 2
                );
                ctx.fillStyle = '#000000';
                ctx.fill();
                
                // 绘制敌人生命值条
                const healthBarWidth = enemy.radius * 2;
                const healthBarHeight = 3;
                const healthPercentage = enemy.health / (enemy.radius * 2);
                
                // 生命值条背景
                ctx.fillStyle = '#660000';
                ctx.fillRect(
                    enemy.x - healthBarWidth / 2, 
                    enemy.y - enemy.radius - 5, 
                    healthBarWidth, 
                    healthBarHeight
                );
                
                // 实际生命值
                ctx.fillStyle = '#00cc00';
                ctx.fillRect(
                    enemy.x - healthBarWidth / 2, 
                    enemy.y - enemy.radius - 5, 
                    healthBarWidth * healthPercentage, 
                    healthBarHeight
                );
            });
            
            // 绘制爆炸效果
            gameState.explosions.forEach(explosion => {
                // 创建径向渐变
                const gradient = ctx.createRadialGradient(
                    explosion.x, explosion.y, 0,
                    explosion.x, explosion.y, explosion.radius
                );
                
                gradient.addColorStop(0, `${explosion.color}FF`);
                gradient.addColorStop(1, `${explosion.color}${Math.floor(explosion.alpha * 255).toString(16).padStart(2, '0')}`);
                
                // 绘制爆炸
                ctx.beginPath();
                ctx.arc(explosion.x, explosion.y, explosion.radius, 0, Math.PI * 2);
                ctx.fillStyle = gradient;
                ctx.fill();
            });
            
            // 绘制粒子效果
            gameState.particles.forEach(particle => {
                ctx.beginPath();
                ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
                ctx.fillStyle = `rgba(${hexToRgb(particle.color)}, ${particle.alpha})`;
                ctx.fill();
            });
             // 绘制环形冲击波粒子
    gameState.particles.forEach(particle => {
        if (particle.type === 'radialWave') {
            ctx.beginPath();
            const scale = (particle.startLifespan - particle.lifespan) / particle.startLifespan;
            const currentRadius = particle.radius + (particle.maxRadius - particle.radius) * scale;
            const gradient = ctx.createRadialGradient(
                particle.x, particle.y, 0,
                particle.x, particle.y, currentRadius
            );
            gradient.addColorStop(0, `rgba(0, 255, 255, ${particle.alpha})`);
            gradient.addColorStop(1, `rgba(0, 255, 255, 0)`);
            ctx.fillStyle = gradient;
            ctx.arc(particle.x, particle.y, currentRadius, 0, Math.PI * 2);
            ctx.fill();
        }
    });
    

            // 绘制头顶等级
            if (gameState.levelIndicator.alpha > 0) {
                ctx.font = `bold ${24 * gameState.levelIndicator.alpha}px Arial`;
                ctx.fillStyle = `rgba(0, 255, 0, ${gameState.levelIndicator.alpha})`;
                ctx.textAlign = 'center';
                ctx.fillText(
                    `Lv.${gameState.player.level}`,
                    gameState.levelIndicator.x,
                    gameState.levelIndicator.y
                );
                
                // 渐隐效果
                gameState.levelIndicator.alpha -= 0.01;
            }
        }
    </script>
</body>
</html>
    